import type { MenuResponse } from '@/services/modules';
import { createTree } from '../utils/createTree';
import { mockMenu } from '@/services/api';
import router from '.';
import { useUserStore } from '@/stores/userStore';
import { useApi } from '@/hooks/useApi';

const pages = () => {
  const views = import.meta.glob('./../views/**/*.vue');
  const result = [];
  for (const key in views) {
    if (Object.prototype.hasOwnProperty.call(views, key)) {
      result.push({
        path: key.replace('../views', '').replace('.vue', '').replace('/index', ''),
        name: key.match(/\/([^\/]+)\/index\.vue/)![1],
        parent: key.match(/\/([^\/]+)\/([^\/]+)\/index\.vue/)![1],
        current: key.match(/\/([^\/]+)\/index\.vue/)![1],
        component: views[key],
        meta: {
          auth: true,
        },
      });
    }
  }
  return result;
};

const { run: menuRun } = useApi(
  mockMenu,
  {},
  {
    immediate: false,
    onSuccess: (data: any) => {
      let routes = [];
      const views = pages();
      let newViews: MenuResponse[] = [];
      newViews = data.map((element: MenuResponse) => {
        return {
          ...views.find((view: any) => view.path === element.path),
          ...element,
          // @ts-ignore
          label: element?.meta?.title,
        };
      });

      routes = createTree(newViews, undefined, (node, parent): boolean => {
        return parent === undefined ? node.pid === 0 : parent && node.pid === parent.id;
      });
      console.log(routes);
      
      setTimeout(() => {
        const userStore = useUserStore();
        // @ts-ignore
        userStore.setMenuList(routes);
      }, 0);

      routes.forEach((item) => {
        // @ts-ignore
        router.addRoute(item);
      });
    },
    onError: (error) => {
      router.push('/login');
      localStorage.clear();
    },
  }
);

export const loadingRouter = async () => {
  // const userStore = useUserStore();

  // await userStore.getUserInfo();
  await menuRun();
  // await mockMenu()
  //   .then(({ code, data }) => {
  //     console.log(code);
  //   })
  //   .catch(() => {
  //     router.push('/login');
  //     localStorage.clear();
  //   });
};
